package com.btpj.shop.service.impl;

import com.btpj.shop.dao.IndexConfigMapper;
import com.btpj.shop.dto.IndexConfigDto;
import com.btpj.shop.dto.param.IndexConfigParam;
import com.btpj.shop.entity.IndexConfig;
import com.btpj.shop.entity.User;
import com.btpj.shop.service.IndexConfigService;
import com.btpj.shop.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class IndexConfigServiceImpl implements IndexConfigService {

    @Resource
    private IndexConfigMapper indexConfigMapper;

    @Resource
    private UserService userService;

    @Transactional
    @Override
    public boolean addIndexConfig(IndexConfigParam indexConfigParam) {
        IndexConfig indexConfig = new IndexConfig();
        BeanUtils.copyProperties(indexConfigParam, indexConfig);
        User currentUser = userService.getUserInfo();
        indexConfig.setCreateUser(currentUser.getId());
        indexConfig.setUpdateUser(currentUser.getId());
        return indexConfigMapper.insertSelective(indexConfig) > 0;
    }

    @Override
    public boolean exists(Long id) {
        return indexConfigMapper.selectByPrimaryKey(id) != null;
    }

    @Transactional
    @Override
    public boolean updateIndexConfig(Long id, IndexConfigParam indexConfigParam) {
        IndexConfig indexConfig = indexConfigMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(indexConfigParam, indexConfig);
        User currentUser = userService.getUserInfo();
        indexConfig.setCreateUser(currentUser.getId());
        indexConfig.setUpdateUser(currentUser.getId());
        return indexConfigMapper.updateByPrimaryKeySelective(indexConfig) > 0;
    }

    @Override
    public List<IndexConfigDto> getIndexConfigsByType(Byte type) {
        return indexConfigMapper.selectIndexConfigsByType(type).stream()
                .map(IndexConfig::indexConfig2Dto)
                .collect(Collectors.toList());
    }

    @Transactional
    @Override
    public boolean deleteByIds(Long[] ids) {
        return indexConfigMapper.deleteByIds(ids) > 0;
    }
}
